<?php

/**
 * 后台用户控制器
 * @author yupoxiong<i@yufuping.com>
 */

namespace app\admin\controller;

use app\admin\exception\AdminServiceException;
use think\Request;
use app\admin\model\AdminRole;
use app\admin\model\AdminUser;
use app\admin\service\AdminUserService;
use app\admin\validate\AdminUserValidate;
use think\response\Json;

class AdminUserController extends Controller
{

    //列表
    public function index(Request $request, AdminUser $model)
    {

        $param = $request->param();
        $data  = $model->scope('where', $param)->paginate(['list_rows' => $this->admin['per_page'], 'query' => $request->get()]);

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, AdminUserService $service, AdminUserValidate $validate)
    {
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }

            try {
                $result   = $service->create($param);
                $redirect = isset($param['_create']) && (int)$param['_create'] === 1 ? URL_RELOAD : URL_BACK;
                return $result ? success('添加成功', $redirect) : error();
            } catch (AdminServiceException $e) {
                return error($e->getMessage());
            }
        }
        $role = AdminRole::column('id,name', 'id');
        $this->assign([
            'role' => $role
        ]);

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, AdminUser $model, AdminUserValidate $validate)
    {

        $data = $model::find($id);
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            $result = $data->update($param);
            return $result ? success('修改成功', URL_CLOSE_REFRESH) : error();
        }

        $role = AdminRole::column('id,name', 'id');
        $this->assign([
            'data' => $data,
            'role' => $role
        ]);
        return $this->fetch('add');
    }


    //删除
    public function del($id, AdminUser $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }


    //启用
    public function enable($id, AdminUser $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 1]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }

      /**
     * 禁用
     * @param mixed $id
     * @param AdminUser $model
     * @return Json
     */
    public function disable($id, AdminUser $model): Json
    {
        $has_admin = false;
        if (is_array($id)) {
            $id = array_map('intval', $id);
            if (in_array(1, $id, true)) {
                $has_admin = true;
            }
        } else if ((int)$id === 1) {
            $has_admin = true;
        }
        if($has_admin){
            return error('超级管理员不能禁用');
        }

        $result = $model->whereIn('id', $id)->update(['status' => 0]);
        return $result ? success('操作成功', [], URL_RELOAD) : error();
    }

    //个人资料
    public function profile(Request $request, AdminUserValidate $validate, AdminUser $model,AdminUserService $service)
    {
        if ($request->isPost()) {
            $param = $request->param();
            switch ($param['update_type']) {
                case 'password':
                    $validate_result = $validate->scene('password')->check($param);
                    if (!$validate_result) {
                        return error($validate->getError());
                    }
                    if (!password_verify($param['password'], base64_decode($this->user->password))) {
                        return error('当前密码不正确');
                    }
                    $service->checkPasswordLevel($param['password']);
                    
                    $this->user->password = $param['new_password'];
                    break;
                case 'avatar':
                    $validate_result = $validate->scene('avatar')->check($param);
                    if (!$validate_result) {
                        return error($validate->getError());
                    }
                    $this->user->avatar =  $param['avatar'];

                    break;
                case 'profile':
                    $validate_result = $validate->scene('nickname')->check($param);
                    if (!$validate_result) {
                        return error($validate->getError());
                    }
                    $this->user->nickname =  $param['nickname'];
                    break;

                default:
                    # code...
                    break;
            }
            if (false !== $this->user->save()) {
                return success('修改成功', URL_RELOAD);
            }
            return error();
        }

        return $this->fetch();
    }
}
